package com.gym.code.generator.impl.dao.sql;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.gym.code.generator.EnumContants.FieldClassType;
import com.gym.code.generator.model.mapping.field.ParameterFieldGenerateModel;
import com.gym.code.generator.model.mapping.field.ParameterListValueFieldGenerateModel;
import com.gym.code.generator.model.mapping.field.ParameterRangeFieldGenerateModel;
import com.gym.code.generator.model.mapping.method.AbstractMethodGenerateModel;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-5-23 下午8:45:17 
 * @param <T>
 */
public abstract class WhereSqlGenerator<T extends AbstractMethodGenerateModel> implements SqlGenerator<T>{
	
	protected String generateWhereColumn(List<ParameterFieldGenerateModel> parameterList) {
		Collections.sort(parameterList);
		StringBuilder result = new StringBuilder();
		for(ParameterFieldGenerateModel item : parameterList) {
			if(item instanceof ParameterRangeFieldGenerateModel){
				result.append(generateParameterBetweenFieldGenerateModel((ParameterRangeFieldGenerateModel)item));
			} else if(item instanceof ParameterListValueFieldGenerateModel){
				result.append(generateParameterListValueFieldGenerateModel((ParameterListValueFieldGenerateModel)item));
			} else {
				result.append(" and ").append(item.getColumnName()).append(" = ?");
			}
		}
		return result.toString();
	}
	
	
	protected String generateParameterBetweenFieldGenerateModel(ParameterRangeFieldGenerateModel model) {
		StringBuilder result = new StringBuilder();
		String fixChar = "'";
		if(FieldClassType.isNumerType(model.getValueType())){
			fixChar = "";
		}
		if(StringUtils.isNotEmpty(model.getBeginName())){
			result.append(" and ").append(model.getColumnName()).append(">")
			.append(fixChar).append("?").append(fixChar);
		}
		if(StringUtils.isNotEmpty(model.getEndName())){
			result.append(" and ").append(model.getColumnName()).append("<")
			.append(fixChar).append("?").append(fixChar);
		}
		return result.toString();
	}
	
	
	protected String generateParameterListValueFieldGenerateModel(ParameterListValueFieldGenerateModel model){
		StringBuilder result = new StringBuilder();
		result.append(" and ").append(model.getColumnName()).append(" in (").append("?").append(")");
		return result.toString();
	}
}
